<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Auth;
use plugin\admin\app\common\Util;
use support\Request;
use support\Response;
use plugin\admin\app\model\QuestionStore;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 题库列表 
 */
class QuestionStoreController extends Crud
{
    
    /**
     * @var QuestionStore
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new QuestionStore;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('question-store/index');
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            $data[$password_filed] = Util::passwordHash($data[$password_filed]);
        }

        if (!Auth::isSupperAdmin() && $this->dataLimit) {
            if (!empty($data[$this->dataLimitField])) {
                $admin_id = $data[$this->dataLimitField];
                if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                    throw new BusinessException('无数据权限');
                }
            }
        }

        $options = array_filter(explode(',', $data['options']));

        $answers = explode(',', $data['answer']);

        if (empty($options)) {
            throw new \Exception('请添加选项');
        }

        if (empty($data['answer'])) {
            throw new \Exception('请设置答案');
        }

        if ($data['type'] == 1 && count($answers) > 1) {
            throw new \Exception('单选答案只能有一个');
        }

        $newOptions = [];
        $start = 65;
        foreach ($options as $option) {
            $newOptions[] = [
                chr($start++) => $option,
            ];
        }

        $start = 64;
        $newAnswers = [];
        foreach ($answers as $answer) {
            $newAnswers[] = chr($start + $answer);
        }

        $data['options'] = json_encode($newOptions, JSON_UNESCAPED_UNICODE);
        $data['answer'] = join(',', $newAnswers);


        return $data;
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('question-store/insert');
    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        if (!Auth::isSupperAdmin() && $this->dataLimit && !empty($data[$this->dataLimitField])) {
            $admin_id = $data[$this->dataLimitField];
            if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                throw new BusinessException('无数据权限');
            }
        }
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            // 密码为空，则不更新密码
            if ($data[$password_filed] === '') {
                unset($data[$password_filed]);
            } else {
                $data[$password_filed] = Util::passwordHash($data[$password_filed]);
            }
        }

        $options = array_filter(explode(',', $data['options']));

        $answers = explode(',', $data['answer']);

        if (empty($options)) {
            throw new \Exception('请添加选项');
        }

        if (empty($data['answer'])) {
            throw new \Exception('请设置答案');
        }

        if ($data['type'] == 1 && count($answers) > 1) {
            throw new \Exception('单选答案只能有一个');
        }

        $newOptions = [];
        $start = 65;
        foreach ($options as $option) {
            $newOptions[] = [
                chr($start++) => $option,
            ];
        }

        $start = 64;
        $newAnswers = [];
        foreach ($answers as $answer) {
            $newAnswers[] = chr($start + $answer);
        }

        $data['options'] = json_encode($newOptions, JSON_UNESCAPED_UNICODE);
        $data['answer'] = join(',', $newAnswers);

        unset($data[$primary_key]);
        return [$id, $data];
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }

        $store = QuestionStore::where('id', $request->get('id'))->first();
        $options = json_decode($store['options'], true);

        $newOptions = [];
        $start = 65;

        foreach ($options as $option) {
            $newOptions[] = $option[chr($start++)];
        }
        $answers = explode(',', $store['answer']);

        $answers = array_map(function(&$item) {
            return ord($item) - 64;
        }, $answers);


        return view('question-store/update', [
            'options' => $newOptions,
            'answers' => $answers
        ]);
    }

}
